<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item :label="$t('procInst.procDefId')" prop="procDefId">
          <el-input
            v-model="queryParams.procDefId"
            :placeholder="$t('procInst.procDefId')"
            @keyup.enter="tableHooks.handleQuery()"
          />
        </el-form-item>
        <el-form-item :label="$t('procInst.procDefKey')" prop="procDefKey">
          <el-input
            v-model="queryParams.procDefKey"
            :placeholder="$t('procInst.procDefKey')"
            @keyup.enter="tableHooks.handleQuery()"
          />
        </el-form-item>
        <el-form-item :label="$t('procInst.category')" prop="category">
          <el-input
            v-model="queryParams.category"
            :placeholder="$t('procInst.category')"
            @keyup.enter="tableHooks.handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tableHooks.handleQuery()">
            {{ $t("common.search") }}
          </el-button>
          <el-button @click="tableHooks.resetQuery()">{{
            $t("common.reset")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 条件查询区域结束 -->
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <!-- 按钮开始 -->
        <el-row justify="space-between" :span="20">
          <el-col :span="12"> </el-col>
          <el-col :span="8" align="right">
            <jmash-column-select
              v-model="tableLabel"
              label-name="flow/monitor"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->

      <!-- 表格开始 -->
      <jmash-table
        class="table-top"
        ref="multipleTableRef"
        row-key="id"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @selection-change="tableSelected"
        @sort-change="handleSort"
        :is-selection="false"
      >
        <template #task="scope">
          <flow-task
            :ref="getRef(scope.data.$index)"
            :proc-inst-id="scope.data.row.id"
            @assignee="handleAssignee"
          ></flow-task>
        </template>

        <!-- suspended -->
        <template #suspended="scope">
          <span>
            <el-switch
              v-model="scope.data.row.suspended"
              :active-value="false"
              :inactive-value="true"
              @click="suspendProcInst(scope.data.row, scope.data.row.suspended)"
            />
          </span>
        </template>
        <template #startUserId="scope">
          {{
            rbacApi.userInfo(scope.data.row.startUserId, vueMetaEnv.APP_TENANT)
              .realName
          }}
        </template>

        <template #startTime="scope">
          <span>{{
            format(new Date(scope.data.row.startTime), "yyyy-MM-dd HH:mm:ss")
          }}</span>
        </template>
        <template #operation="scope">
          <el-button
            type="primary"
            link
            v-hasPerm="['flow:monitor:view']"
            @click="handleViewDiagram(scope.data.row)"
          >
            {{ $t("flow.viewDiagram") }}
          </el-button>
        </template>
      </jmash-table>
      <template #footer>
        <jmash-pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:current-page="queryParams.curPage"
          v-model:page-size="queryParams.pageSize"
          @pagination="tableHooks.getList()"
        />
        &nbsp;
      </template>
    </el-card>
    <procinit-diagram
      v-if="viewDialog.visible"
      v-model="viewDialog.visible"
      :title="viewDialog.title"
      :entity-key="entityKey"
      width="900px"
    />
    <!-- 表格结束 -->
    <Task-transfer-dialog
      :key="taskId"
      v-if="assigneeDialog.visible"
      v-model="assigneeDialog.visible"
      :title="assigneeDialog.title"
      :task-id="taskId"
      :assignee-id="assigneeId"
      @refresh="refresh"
      width="800px"
    />
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive, onActivated } from "vue";
import {
  type TableColumn,
  type DialogRef,
  type TableSort,
  useTableHooks,
  vueMetaEnv,
} from "jmash-core";
import { format } from "date-fns";
import { rbacApi } from "jmash-rbac";

import { useI18n } from "vue-i18n";
const { t } = useI18n();

import { useRoute } from "vue-router";
const route = useRoute();

import type {
  ProcInstReq,
  FlowProcInstKey,
  FlowProcInstModel,
  FlowTaskModel,
} from "@/api/flow/task/types";

import type { FlowSuspendProcInstReq } from "@/api/flow/monitor/types";

import { monitorApi } from "@/api/flow/monitor/index";

import procinitDiagram from "@/views/flow/common/procinst-diagram-dialog.vue";
import flowTask from "./task.vue";

const flowTaskRef = [] as Ref[];
// 计算属性，返回指定索引的 ref
const getRef = (index: number) => {
  return (flowTaskRef[index] = ref());
};

const queryParams = ref<ProcInstReq>({});

const {
  tableHooks,
  multipleTableRef,
  queryFormRef,
  listLoading,
  tableData,
  total,
} = useTableHooks(t, monitorApi, queryParams);

let tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "procInst.no",
    type: "expand",
    width: "60",
    slotName: "task",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "procInst.tenantId",
    prop: "tenantId",
    width: "80",
    isColumn: true,
  },
  {
    label: "procInst.id",
    prop: "id",
    width: "120",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "procInst.name",
    prop: "name",
    width: "150",
    isColumn: true,
  },
  {
    label: "procInst.startUserId",
    prop: "startUserId",
    width: "120",
    slotName: "startUserId",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "procInst.startTime",
    prop: "startTime",
    width: "160",
    slotName: "startTime",
    columnType: "slot",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "procInst.suspended",
    prop: "suspended",
    width: "110",
    slotName: "suspended",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "procInst.businessKey",
    prop: "businessKey",
    width: "120",
    isColumn: true,
  },
  {
    label: "procInst.businessStatus",
    prop: "businessStatus",
    width: "120",
    isColumn: true,
  },
  {
    label: "procInst.processDefinitionName",
    prop: "processDefinitionName",
    sortable: "custom",
    width: "150",
    isColumn: true,
  },
  {
    label: "procInst.processDefinitionId",
    prop: "processDefinitionId",
    width: "200",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "procInst.description",
    prop: "description",
    isColumn: true,
  },
  {
    label: "common.operate",
    width: "80",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);

//编辑Dialog
const editDialog = ref({
  title: t("common.edit"),
  visible: false,
} as DialogRef);

//查看Dialog
const viewDialog = ref({
  title: t("flow.viewDiagram"),
  visible: false,
} as DialogRef);

//分配Dialog
const assigneeDialog = ref({
  title: t("common.edit"),
  visible: false,
} as DialogRef);

//传递的任务实例行
let taskInstNo = -1;
//传递的任务ID
const taskId = ref<string>("");
// 传递的分配用户ID
const assigneeId = ref<string>("");
// 分配
function handleAssignee(row: FlowTaskModel) {
  taskId.value = row.id as string;
  assigneeId.value = row.assignee as string;
  assigneeDialog.value.title = t("flow.assignee");
  assigneeDialog.value.visible = true;
  //找到分配用户的行
  tableHooks.tableData.value.forEach((element: FlowProcInstModel, index) => {
    if (element.id === row.processInstanceId) {
      taskInstNo = index;
    }
  });
}

let entityKey = reactive<FlowProcInstKey>({});

// 新增
function handleAdd() {
  entityKey = reactive<FlowProcInstKey>({});
  editDialog.value.title = t("flow.deploy");
  editDialog.value.visible = true;
}

// 查看流程图
function handleViewDiagram(row: FlowProcInstModel) {
  entityKey.procInstId = row.id;
  viewDialog.value.visible = true;
}

// 行选择
function tableSelected(value: FlowProcInstModel[]) {
  tableHooks.selectionRows.value = value;
}

//处理排序
function handleSort(sort: TableSort) {
  //Flowable 排序方式.
  let orderName = "";
  if (sort.prop == "id") {
    orderName = "RES.ID_";
  } else if (sort.prop == "processDefinitionName") {
    orderName = "P.KEY_";
  } else if (sort.prop == "processDefinitionId") {
    orderName = "RES.PROC_DEF_ID_";
  } else if (sort.prop == "startTime") {
    orderName = "RES.START_TIME_";
  }
  tableHooks.handleSort(orderName, sort.order);
}

//挂起或激活
function suspendProcInst(row: FlowProcInstModel, suspend: boolean) {
  let req = {
    requestId: Math.random() * 10 + "",
    procInstId: row.id,
    suspend: suspend,
  } as FlowSuspendProcInstReq;
  monitorApi.suspendProcInst(req).then((res) => {
    tableHooks.getList();
  });
}

/**
 * 从子组件传过来的事件，刷新列表
 *
 * @returns {void}
 */
function refresh(value: boolean) {
  if (value && taskInstNo >= 0) {
    flowTaskRef[taskInstNo].value.refresh(value);
  }
}

if (route.query.procDefId) {
  queryParams.value.procDefId = route.query.procDefId as string;
}

//查询数据.
onActivated(() => {
  tableHooks.getList();
});
</script>
